package de.tud.etit.blipz.services.json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;

import de.tud.etit.blipz.entities.Contact;
import de.tud.etit.blipz.entities.Position;
import de.tud.etit.blipz.entities.User;
import de.tud.etit.blipz.exceptions.ApplicationException;

public class UserService extends JsonService {

	private final static String URL = "http://ec2-54-216-30-89.eu-west-1.compute.amazonaws.com:3000/users";

	private final Gson gson;

	public UserService() {
		GsonBuilder builder = new GsonBuilder();
		builder.registerTypeAdapter(Position.class, new PositionDeserializer());
		builder.registerTypeAdapter(Position.class, new PositionSerializer());
		builder.registerTypeAdapter(Contact.class, new ContactSerializer());
		builder.registerTypeAdapter(Contact.class, new ContactDeserializer());
		builder.registerTypeAdapter(User.class, new UserSerializer());
		builder.registerTypeAdapter(User.class, new UserDeserializer());

		gson = builder.create();
	}

	public void register(User user) {
		String jsonData = this.gson.toJson(user);

		this.post(URL, jsonData);
	}

	public List<Contact> getContacts(String mobileNr) {
		String url = URL + "/" + mobileNr + "/contacts";
		List<Contact> contacts = new ArrayList<Contact>();

		try {
			HttpResponse<JsonNode> jsonResponse = this.get(url);

			for (int i = 0; i < jsonResponse.getBody().getArray().length(); i++) {
				Contact contact = null;

				try {
					contact = gson.fromJson(jsonResponse.getBody().getArray()
							.getString(i), Contact.class);

					if (contact != null) {
						contacts.add(contact);
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return contacts;
	}

	public void sendBlip(Position position, String mobileNr) {
		String url = URL + "/" + mobileNr + "/position";
		String jsonData = this.gson.toJson(position);
		this.put(url, jsonData);
	}

	public void addContact(String mobileNr, Contact contact) {
		String url = URL + "/" + mobileNr + "/contacts/"
				+ contact.getMobileNr();

		this.put(url, "");
	}

	public Position getPosition(String ownMobileNr, Contact contact) {
		String url = URL + "/" + ownMobileNr + "/contacts/"
				+ contact.getMobileNr() + "/position";

		Position position = null;
		try {
			HttpResponse<JsonNode> jsonResponse = this.get(url);
			String postionJsonString = jsonResponse.getBody().getArray()
					.getString(0);

			position = gson.fromJson(postionJsonString, Position.class);
		} catch (JSONException ex) {
			throw new ApplicationException();
		}

		return position;
	}
}
